import Route from '@/utils/Route.js';
import Http from '@/utils/Http.js';
const getWxappId = () => {
	return 10001;
}
/**
 * 显示失败提示框
 */
const showError = (msg, callback) => {
	uni.showModal({
		title: '友情提示',
		content: msg,
		showCancel: false,
		success(res) {
			// callback && (setTimeout(function() {
			//   callback();
			// }, 1500));
			callback && callback();
		}
	});
}

/**
 * 显示成功提示框
 */
const showSuccess = (msg, callback) => {
	uni.showToast({
		title: msg,
		icon: 'success',
		mask: true,
		duration: 1500,
		success() {
			callback && (setTimeout(function() {
				callback();
			}, 1500));
		}
	});
};

/**
 * 验证登录
 */
const checkIsLogin = () => {
	return uni.getStorageSync('token') != '' && uni.getStorageSync('user_id') != '';
};

/**
 * 对象转URL
 */
const urlEncode = (data) => {
	var _result = [];
	for (var key in data) {
		var value = data[key];
		console.log(key)
		if (value.constructor == Array) {
			value.forEach(_value => {
				_result.push(key + "=" + _value);
			});
		} else {
			_result.push(key + '=' + value);
		}
	}
	return _result.join('&');
};

/**
 * 是否在数组内
 */
const inArray = (search, array) => {
	for (var i in array) {
		if (array[i] == search) {
			return true;
		}
	}
	return false;
};

/**
 * 生成转发的url参数
 */
const getShareUrlParams = (params) => {
	return urlEncode(Object.assign({
		referee_id: getRefereeId()
	}, params));
};
/**
 * 当前用户id
 */
const getUserId = () => {
	return uni.getStorageSync('user_id');
};
/**
 * 当前用户referee_id
 */
const getRefereeId = () => {
	return uni.getStorageSync('referee_id');
};
/**
 * 生成统一分享链接
 */
const getShareUrl = (path = '', params = {}) => {
	if (!path) {
		path = 'pages/login/index';
	}
	return getSite() + '/' + path + '?' + getShareUrlParams({
		wxapp_id: getWxappId(),
		...params
	});
	// http://front.deyuelou.top/pages/account/register?wxapp_id=10001&referee_id=000B

}
/**
 * 获取场景值(scene)
 */
const getSceneData = (query) => {
	return query.scene ? scene_decode(query) : query;
};
/**
 * 获取当前页面路径
 */
const getPagePath = () => {
	const pages = getCurrentPages();
	const page = pages[pages.length - 1];
	return page.route

}

/**
 * scene解码
 */
const sceneDecode = (e) => {
	if (e === undefined)
		return {};
	let scene = decodeURIComponent(e),
		params = scene.split(','),
		data = {};
	for (let i in params) {
		var val = params[i].split(':');
		val.length > 0 && val[0] && (data[val[0]] = val[1] || null)
	}
	return data;
}

const isWechat = () => {
	var ua = window.navigator.userAgent.toLowerCase();
	if (ua.match(/micromessenger/i) == 'micromessenger') {
		return true;
	}
	return false;
};

const regionHandle = (data = [], provinceIndex = 0, cityIndex = 0, areaIndex = 0) => {
	// 初始化基础数据
	const regionRange = [
		[],
		[],
		[]
	]
	const regionValue = [provinceIndex, cityIndex, areaIndex]
	// 判断省位置是否超过数据
	if (provinceIndex >= data.length) {
		const regionValue = [0, 0, 0];
		provinceIndex = 0;
		cityIndex = 0;
		areaIndex = 0;
	}
	for (let i = 0; i < data.length; i++) {
		regionRange[0].push(data[i].label)
	}
	// 判断市位置是否超过数据
	const cityList = data[provinceIndex].children;
	if (cityIndex >= cityList.length) {
		const regionValue = [provinceIndex, 0, 0];
		cityIndex = 0;
		areaIndex = 0;
	}

	for (let j = 0; j < cityList.length; j++) {
		regionRange[1].push(cityList[j].label)
	}
	// 判断区位置是否超过数据
	const areaList = cityList[cityIndex].children;
	console.log(areaIndex)
	if (areaIndex >= areaList.length) {
		const regionValue = [provinceIndex, cityIndex, 0];
		areaIndex = 0;
	}
	for (let k = 0; k < areaList.length; k++) {
		regionRange[2].push(areaList[k].label)
	}
	const regionPickerData = {
		regionRange,
		regionValue
	};
	return regionPickerData;
}

/**
 * 格式化日期格式 (用于兼容ios Date对象)
 */
const formatDate = (time) => {
	// 将xxxx-xx-xx的时间格式，转换为 xxxx/xx/xx的格式 
	return time.replace(/\-/g, "/");
};
const getSite = () => {
	return 'https://m.qzyzjk.com'
}


/**
 * 记录推荐人id
 */
const setSuperiorId = (superiorId) => {
	uni.setStorageSync('superior_id', superiorId)
};

/**
 * 获取推荐人id
 */
const getSuperiorId = () => {
	return uni.getStorageSync('superior_id') || ''
};

const formatRichText = (html) => {
	let newContent = html.replace(/<img[^>]*>/gi, function(match, capture) {
		match = match.replace(/style="[^"]+"/gi, '').replace(/style='[^']+'/gi, '');
		match = match.replace(/width="[^"]+"/gi, '').replace(/width='[^']+'/gi, '');
		match = match.replace(/height="[^"]+"/gi, '').replace(/height='[^']+'/gi, '');
		return match;
	});
	newContent = newContent.replace(/style="[^"]+"/gi, function(match, capture) {
		match = match.replace(/width:[^;]+;/gi, 'max-width:100%;').replace(/width:[^;]+;/gi, 'max-width:100%;');
		return match;
	});
	newContent = newContent.replace(/<br[^>]*\/>/gi, '');
	// newContent = newContent.replace(/\<img/gi, '<img style="max-width:100%;height:auto;display:block;margin-top:0;margin-bottom:0;"');
	return newContent;
}

const redirectToCurrentPage = () => {
	try {
		const currentPage = uni.getStorageSync('currentPage') || null;
		uni.removeStorageSync('currentPage');
		let pageIndex = null;
		if (currentPage) {
			const route = currentPage.route || '';
			const params = currentPage.params || '';
			const currentPages = getCurrentPages();
			for (let i = 0; i < currentPages.length; i++) {
				if (route == currentPages[i].route && params == urlEncode(currentPages[i].options)) {
					pageIndex = i;
					break;
				}
			}
			if (pageIndex > 0 && currentPages.length - pageIndex - 1 > 0) {
				Route.navigateBack({
					delta: currentPages.length - pageIndex - 1,

				})
			} else {
				Route.redirectTo({
					url: '/' + route + '?' + params
				})
			}

		} else {
			Route.reLaunch();
		}
	} catch (e) {
		Route.reLaunch();
	}

}

const getUserInfo = (success, fail, complete) => {
	const token = uni.getStorageSync('token') || null;
	if (token) {
		Http.post(
			Http.api.getUserInfo, {
				token
			},
			res => {
				uni.setStorageSync('user_id', res.data.userInfo.user_id);
				uni.setStorageSync('referee_id', res.data.userInfo.code);
				success && success(res);
			},
			e => {
				fail && fail(res);
			},
			() => {
				complete && complete()
			}
		);
	} else {
		success && success();
	}
}

export default {
	getWxappId,
	showError,
	showSuccess,
	urlEncode,
	checkIsLogin,
	inArray,
	getShareUrlParams,
	getUserId,
	getSceneData,
	sceneDecode,
	getRefereeId,
	getShareUrl,
	isWechat,
	regionHandle,
	formatDate,
	getSite,
	setSuperiorId,
	getSuperiorId,
	getPagePath,
	formatRichText,
	redirectToCurrentPage,
	getUserInfo
}
